import os from 'os'
import logger from './logger.js'

export class SystemMonitor {
  constructor() {
    this.stats = {
      startTime: Date.now(),
      requests: 0,
      errors: 0,
      avgResponseTime: 0
    }
    
    this.startPeriodicCheck()
  }

  // 记录请求
  recordRequest(duration) {
    this.stats.requests++
    this.stats.avgResponseTime = 
      (this.stats.avgResponseTime * (this.stats.requests - 1) + duration) / this.stats.requests
  }

  // 记录错误
  recordError() {
    this.stats.errors++
  }

  // 获取系统状态
  getStatus() {
    const uptime = Date.now() - this.stats.startTime
    
    return {
      uptime: Math.floor(uptime / 1000),
      memory: {
        total: os.totalmem(),
        free: os.freemem(),
        used: os.totalmem() - os.freemem()
      },
      cpu: {
        load: os.loadavg(),
        cores: os.cpus().length
      },
      requests: {
        total: this.stats.requests,
        errors: this.stats.errors,
        avgResponseTime: Math.round(this.stats.avgResponseTime)
      }
    }
  }

  // 定期检查系统状态
  startPeriodicCheck() {
    setInterval(() => {
      const status = this.getStatus()
      const memoryUsage = (status.memory.used / status.memory.total) * 100
      
      if (memoryUsage > 80) {
        logger.warn('High memory usage detected', {
          memoryUsage: `${memoryUsage.toFixed(2)}%`,
          freeMemory: `${(status.memory.free / 1024 / 1024).toFixed(2)}MB`
        })
      }
      
      if (status.cpu.load[0] > status.cpu.cores) {
        logger.warn('High CPU load detected', {
          load: status.cpu.load[0],
          cores: status.cpu.cores
        })
      }
    }, 60000) // 每分钟检查一次
  }
}

export const systemMonitor = new SystemMonitor() 